/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-09-02     RealThread   first version
 */

#include <rtthread.h>
#include <board.h>
#include <drv_common.h>
#include "ports/drv_mpu.h"
#include "ports/drv_sdram.h"

#if defined(BSP_USING_SDRAM) && defined(RT_USING_MEMHEAP_AS_HEAP)
static struct rt_memheap system_heap;
#endif

struct rt_memheap dma_heap;
struct rt_memheap fsmc_heap;

RT_WEAK void rt_hw_board_init()
{
    extern void hw_board_init(char *clock_src, int32_t clock_src_freq, int32_t clock_target_freq);

    /* Configure the MPU attributes as Write Through */
    bsp_mpu_hw_init();

    /**************************************************************
                       内存分布
    1.  0x20013000---             DTCM，不缓存               dma专用内存


    2.  0x20020000---            内部sram1，缓存WB           系统堆内存


    3.  0xc0000000---            SDRAM ，缓存WB              堆内存

    串口dma，sd卡dma,tftp dma使用系统堆内存，需要使用   SCB_CleanDCache() 写 和 SCB_CleanInvalidateDCache() 读  共享时dma可使用，不共享时外部dma不可用
    网口用DTCM内存，共享/不共享 dma都可以使用
    **************************************************************/

    /* Heap initialization */
#if defined(BSP_USING_SDRAM) && defined(RT_USING_MEMHEAP_AS_HEAP)
    bsp_sdram_hw_init();
    rt_system_heap_init((void *) HEAP_BEGIN, (void *) HEAP_END);
    rt_memheap_init(&system_heap, "sdram", (void *)SDRAM_BEGIN, SDRAM_SIZE);

    rt_memheap_init(&dma_heap, "dma_heap", (void *)0x20013000, 0xA000); //////////////dma专用内存
    rt_memheap_init(&fsmc_heap, "fsmc_heap", (void *)0xC0800000, 0x1000000);    //////////////fsmc专用内存
#endif

    hw_board_init(BSP_CLOCK_SOURCE, BSP_CLOCK_SOURCE_FREQ_MHZ, BSP_CLOCK_SYSTEM_FREQ_MHZ);

    /* Set the shell console output device */
#if defined(RT_USING_DEVICE) && defined(RT_USING_CONSOLE)
    rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
#endif

    /* Board underlying hardware initialization */
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif

}

void *rt_dma_realloc(rt_size_t size)
{
    void *ptr;

    /* try to allocate in system heap */
    ptr = rt_memheap_alloc(&dma_heap, size);

    return ptr;
}
RTM_EXPORT(rt_dma_realloc);


void *rt_fsmc_realloc(rt_size_t size)
{
    void *ptr;

    /* try to allocate in system heap */
    ptr = rt_memheap_alloc(&fsmc_heap, size);

    return ptr;
}
RTM_EXPORT(rt_fsmc_realloc);

